<template>
  <div class="home-wrap">
    <h2>欢迎进入智慧课程平台</h2>

    <!-- 系统通知模块 -->
    <div class="system-notifications-section">
      <h3 class="system-notifications-title">系统通知</h3>
      <div class="notification" v-for="(notification, index) in systemNotifications" :key="index">
        <h4 class="notification-title">{{ notification.title }}</h4>
        <p class="notification-message">{{ notification.content }}</p>
      </div>
      <div class="no-system-notifications" v-if="systemNotifications.length === 0">没有新系统通知</div>
    </div>

    <!-- 搜索用户收藏夹模块 -->
    <div class="search-section">
      <input
        type="text"
        v-model="searchUserId"
        placeholder="输入用户ID"
        class="search-input"
      />
      <button @click="searchUserFavorites" class="search-btn">搜索用户收藏夹</button>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchedUserFavorites" class="favorites-section">
      <h3 class="favorites-title">用户ID: {{ searchedUserId }} 的收藏夹</h3>
      <div class="folder">
        <h4 class="folder-title">{{ searchedUserFavorites.name }}</h4>
        <div class="files-container">
          <div
            class="file-item"
            v-for="(note, noteIndex) in searchedUserFavorites.notes"
            :key="noteIndex"
          >
            <h4 class="note-title">{{ note.title }}</h4>
            <p class="note-content">{{ note.content }}</p>
            <p class="note-file-id">文件ID: {{ note.id }}</p>
            
            <!-- 点赞功能 -->
            <div class="likes-section">
              <span>点赞数: {{ note.likesCount }}</span>
              <button @click="likeFile(note.id, noteIndex, true)" class="like-btn">点赞</button>
            </div>

            <button @click="openFile(note)" class="open-file-btn">打开文件</button>
            <button @click="downloadFile(note.id)" class="download-btn">下载</button>
          </div>
          <div class="no-files" v-if="searchedUserFavorites.notes.length === 0">没有文件</div>
        </div>
      </div>
    </div>

    <!-- 当前用户的收藏夹模块 -->
    <div class="favorites-section">
      <h3 class="favorites-title">我的收藏夹</h3>
      <div class="folder">
        <h4 class="folder-title">收藏夹</h4>
        <div class="files-container">
          <div
            class="file-item"
            v-for="(note, noteIndex) in favoriteFolder.notes"
            :key="noteIndex"
          >
            <h4 class="note-title">{{ note.title }}</h4>
            <p class="note-content">{{ note.content }}</p>
            <p class="note-file-id">文件ID: {{ note.id }}</p>

            <!-- 点赞功能 -->
            <div class="likes-section">
              <span>点赞数: {{ note.likesCount }}</span>
              <button @click="likeFile(note.id, noteIndex, false)" class="like-btn">点赞</button>
            </div>

            <button @click="openFile(note)" class="open-file-btn">打开文件</button>
            <button @click="removeNote(noteIndex)" class="remove-btn">移除</button>
            <button @click="downloadFile(note.id)" class="download-btn">下载</button>
          </div>
          <div class="no-files" v-if="favoriteFolder.notes.length === 0">没有文件</div>
        </div>
        <input
          type="file"
          @change="handleFileSelect($event)"
          class="file-input"
          accept=".txt,.doc,.pdf"
        />
        <button @click="addFile" class="add-file-btn">添加文件</button>
        <div class="toggle-public-section">
          <label for="isPublicCheckbox">公开收藏夹</label>
          <input type="checkbox" id="isPublicCheckbox" v-model="favoriteFolder.isPublic" @change="togglePublic" />
        </div>
      </div>
    </div>

    <!-- 用户通知模块 -->
    <div class="notifications-section">
      <h3 class="notifications-title">用户通知</h3>
      <div class="notification" v-for="(notification, index) in notifications" :key="index">
        <p class="notification-message">{{ notification }}</p>
      </div>
      <div class="no-notifications" v-if="notifications.length === 0">没有新通知</div>
    </div>

    <!-- 关注列表模块 -->
    <div class="following-section">
      <h3 class="following-title">我关注的用户</h3>
      <div v-if="followingList.length > 0">
        <div class="following-item" v-for="(user, index) in followingList" :key="index">
          <p class="user-id">用户ID: {{ user.userId }}</p>
          <button @click="unfollowUser(user.userId, index)" class="unfollow-btn">取消关注</button>
        </div>
      </div>
      <div class="no-following" v-else>您尚未关注任何用户。</div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import Config from '../common/config.js'; // 引入配置文件

export default {
  name: "Home",
  data() {
    return {
      searchUserId: '', // 存储搜索的用户ID
      searchedUserId: '', // 被搜索到的用户ID
      searchedUserFavorites: null, // 被搜索到的用户收藏夹
      systemNotifications: [], // 系统通知内容
      favoriteFolder: { // 当前用户的收藏夹
        name: '我的收藏夹',
        notes: [],
        isPublic: false,
        likes: 0
      },
      selectedFile: null,
      selectedFileName: '',
      notifications: [
        '您有一个新课程更新。',
        '请注意，您的作业截止日期已更改。',
        '系统维护将在本周末进行。'
      ],
      followingList: []
    };
  },
  methods: {
    // 获取系统通知
    fetchSystemNotifications() {
      axios.get(`${Config.backEndUrl}/notifications`)
        .then(response => {
          this.systemNotifications = response.data.map(notification => ({
            title: notification.title,
            content: notification.content
          }));
        })
        .catch(error => {
          console.error('无法获取系统通知', error);
        });
    },

    // 其他方法保持不变...
    togglePublic() {
      const userId = this.$store.state.status.userId;
      const isPublic = !!this.favoriteFolder.isPublic;

      axios.put(`${Config.backEndUrl}/favourites/visibility`, null, {
        params: {
          userId: userId,
          isPublic: isPublic
        },
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .catch(error => {
        console.error('更新收藏夹公开状态失败', error);
      });
    },

    likeFile(fileId, noteIndex, isSearchedUser) {
      axios.post(`${Config.backEndUrl}/favourites/like`, null, {
        params: {
          fileId: fileId
        }
      })
      .then(response => {
        if (isSearchedUser) {
          this.searchedUserFavorites.notes[noteIndex].likesCount = response.data.likesCount;
        } else {
          this.favoriteFolder.notes[noteIndex].likesCount = response.data.likesCount;
        }
      })
      .catch(error => {
        console.error('点赞失败', error);
      });
    },

    searchUserFavorites() {
      axios.get(`${Config.backEndUrl}/favourites/list`, {
        params: {
          userId: this.searchUserId
        }
      })
      .then(response => {
        const userFavoritesList = response.data;

        if (userFavoritesList && userFavoritesList.length > 0) {
          const userFavorites = userFavoritesList[0];

          if (userFavorites.public) {
            this.searchedUserId = this.searchUserId;
            this.searchedUserFavorites = {
              name: `用户${this.searchUserId}的收藏夹`,
              notes: userFavoritesList.map(fav => ({
                title: fav.fileName,
                content: fav.fileData,
                id: fav.fileId,
                likesCount: fav.likesCount
              }))
            };
          } else {
            alert("该用户的收藏夹不可见或不存在");
            this.searchedUserFavorites = null;
          }
        } else {
          alert("未找到该用户的收藏夹");
          this.searchedUserFavorites = null;
        }
      })
      .catch(error => {
        console.error('无法获取用户收藏夹', error);
        alert("该用户的收藏夹无法访问");
        this.searchedUserFavorites = null;
      });
    },

    handleFileSelect(event) {
      const file = event.target.files[0];
      if (file) {
        this.selectedFile = file;
        this.selectedFileName = file.name;
      }
    },

    addFile() {
      if (this.selectedFile) {
        this.uploadFile(); 
      }
    },

    uploadFile() {
      const formData = new FormData();
      formData.append('userId', this.$store.state.status.username);
      formData.append('file', this.selectedFile);

      axios.post(`${Config.backEndUrl}/favourites/uploadAndAdd`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      .then(() => {
        const fileTitle = this.selectedFileName;
        const fileContent = "文件名：" + this.selectedFileName;

        this.favoriteFolder.notes.push({
          title: fileTitle,
          content: fileContent,
          url: URL.createObjectURL(this.selectedFile),
          id: Date.now(),
          likesCount: 0
        });

        this.selectedFile = null;
        this.selectedFileName = '';
      })
      .catch(error => {
        console.error('文件上传失败', error);
      });
    },

    openFile(note) {
      window.open(note.url, '_blank');
    },

    removeNote(noteIndex) {
      const note = this.favoriteFolder.notes[noteIndex];
      const fileId = String(note.id);

      axios.delete(`${Config.backEndUrl}/favourites/remove`, {
        params: {
          userId: this.$store.state.status.userId,
          fileId: fileId
        }
      })
      .then(() => {
        this.favoriteFolder.notes.splice(noteIndex, 1);
      })
      .catch(error => {
        console.error('删除文件失败', error);
      });
    },

    downloadFile(fileId) {
      axios.get(`${Config.backEndUrl}/favourites/download`, {
        params: {
          fileId: fileId
        },
        responseType: 'blob'
      })
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');

        let fileName = '';
        const disposition = response.headers['content-disposition'];

        if (disposition && disposition.includes('filename=')) {
          fileName = decodeURIComponent(disposition.split('filename=')[1].replace(/['"]/g, ''));
        } else {
          fileName = fileId;
        }

        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
      .catch(error => {
        console.error('文件下载失败', error);
      });
    },

    fetchFollowingList() {
      const userId = this.$store.state.status.userId;

      axios.get(`${Config.backEndUrl}/user/following`, {
        params: {
          userId: userId
        }
      })
      .then(response => {
        this.followingList = response.data;
      })
      .catch(error => {
        console.error('无法获取关注列表', error);
      });
    },

    unfollowUser(followingUserId, index) {
      const userId = this.$store.state.status.userId;

      axios.delete(`${Config.backEndUrl}/user/unfollow`, {
        params: {
          userId: userId,
          followingUserId: followingUserId
        }
      })
      .then(() => {
        this.followingList.splice(index, 1);
      })
      .catch(error => {
        console.error('取消关注失败', error);
      });
    },

    fetchUserFavorites() {
      const userId = this.$store.state.status.userId;

      axios.get(`${Config.backEndUrl}/favourites/list`, {
        params: {
          userId: userId
        }
      })
      .then(response => {
        const favorites = response.data;

        favorites.forEach(favorite => {
          this.favoriteFolder.isPublic = favorite.public;
          this.favoriteFolder.likes = favorite.likesCount;
        });

        this.favoriteFolder.notes = favorites.map(favorite => ({
          title: favorite.fileName,
          content: favorite.fileData,
          url: '',
          id: favorite.fileId,
          likesCount: favorite.likesCount
        }));
      })
      .catch(error => {
        console.error('无法获取收藏夹内容', error);
      });
    }
  },
  mounted() {
    this.fetchSystemNotifications(); // 获取系统通知
    this.fetchUserFavorites();
    this.fetchFollowingList();
  }
};
</script>

<style>

.home-wrap {
  height: 100%;
  width: 100%;
}

.system-notifications-section {
  margin-top: 20px;
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.system-notifications-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.notification {
  margin-top: 10px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.notification-title {
  font-size: 16px;
  color: #555;
  margin: 0;
}

.notification-message {
  font-size: 14px;
  color: #777;
  margin: 5px 0;
}

.no-system-notifications {
  font-size: 14px;
  color: #999;
  text-align: center;
  margin-top: 10px;
}

.search-section {
  margin-top: 20px;
  margin-bottom: 20px;
}

.search-input {
  padding: 5px;
  width: 200px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.search-btn {
  padding: 5px 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.favorites-section {
  margin-top: 20px;
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.favorites-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.folder {
  margin: 10px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.folder-title {
  font-size: 18px;
  color: #333;
}

.files-container {
  max-height: 200px; /* 限制文件区高度 */
  overflow-y: auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 5px;
}

.file-item {
  border-bottom: 1px solid #eee;
  padding: 5px 0;
}

.note-title {
  font-size: 16px;
  color: #555;
  margin: 0;
}

.note-content {
  font-size: 14px;
  color: #777;
  margin: 5px 0;
}

.note-file-id {
  font-size: 12px;
  color: #888;
  margin: 5px 0;
}

.open-file-btn,
.remove-btn,
.add-file-btn,
.download-btn {
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
}

.open-file-btn:hover,
.remove-btn:hover,
.add-file-btn:hover,
.download-btn:hover {
  background-color: #d32f2f;
}

.no-files,
.no-notifications {
  font-size: 14px;
  color: #999;
  text-align: center;
  margin-top: 10px;
}

.file-input {
  margin-top: 10px;
}

.add-file-btn {
  margin-top: 5px;
  background-color: #4CAF50;
}

.add-file-btn:hover {
  background-color: #388E3C;
}

/* 点赞功能样式 */
.likes-section {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.like-btn {
  background-color: #ff9800;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-left: 10px;
}

.like-btn:hover {
  background-color: #fb8c00;
}

.likes-section span {
  font-size: 14px;
  color: #555;
}

.following-section {
  margin-top: 20px;
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.following-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.following-item {
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-bottom: 10px;
}

.unfollow-btn {
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
}

.unfollow-btn:hover {
  background-color: #d32f2f;
}

.no-following {
  font-size: 14px;
  color: #999;
  text-align: center;
  margin-top: 10px;
}
</style>